package org.wanda.pv.controller;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.random.R;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.wanda.pv.controller.business.ExcelController;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.model.basic.*;
import org.wanda.pv.model.basic.System;
import org.wanda.pv.model.hy.HyDrawing;
import org.wanda.pv.model.hy.HyNodeInfo;
import org.wanda.pv.model.hy.HySync2dDrawInfo;
import org.wanda.pv.model.hy.HyTree;
import org.wanda.pv.model.test.MyTest;
import org.wanda.pv.service.file.FileUploadService;
import org.wanda.pv.service.hy.HyDrawingService;
import org.wanda.pv.service.hy.HyNodeInfoService;
import org.wanda.pv.util.HyUtil;
import org.wanda.pv.util.RotateImage;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/test")
@SuppressWarnings("all")
public class TestController{
     private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Dao dao;

    @Autowired
    FileUploadService fileUploadService;
    @Autowired
    HyNodeInfoService hyNodeInfoService;
    @Autowired
    HyDrawingService hyDrawingService;

    @RequestMapping("/tt")
    public Object getTT(){
        List<HyTree> hyTrees = dao.query(HyTree.class, Cnd.where("parent_id","=","116"));
        hyTrees.forEach(hyTree -> {
            List<HyTree> hyTreeList = dao.query(HyTree.class, Cnd.where("parent_id","=",hyTree.getId()));
            hyTree.setChildren(hyTreeList);
            logger.info("个数 ：" + hyTreeList.size());
        });

        return hyTrees;
     }


    @RequestMapping("xz")
    public Object testImgRotate() throws Exception {
        File srcFile = new File("/Users/dengwubo/wandaPV/upload/files/201811/1543224360238.jpg");
        BufferedImage src = ImageIO.read(srcFile);
        //顺时针旋转90度
        BufferedImage des1 = RotateImage.Rotate(src, 90);
        ImageIO.write(des1, "jpg", new File("/Users/dengwubo/image/90.jpg"));
        //顺时针旋转180度
        BufferedImage des2 = RotateImage.Rotate(src, 180);
        ImageIO.write(des2, "jpg", new File("/Users/dengwubo/image/180.jpg"));
        //顺时针旋转270度
        BufferedImage des3 = RotateImage.Rotate(src, 270);
        ImageIO.write(des3, "jpg", new File("/Users/dengwubo/image/270.jpg"));  //顺时针旋转270度
        BufferedImage des4 = RotateImage.Rotate(src, 360);
        ImageIO.write(des4, "jpg", new File("/Users/dengwubo/image/360.jpg"));

        return Result.success();
    }



    @RequestMapping("/sync")
    public void syncDrawing(){
    }

    @PostMapping(value = "/ws/v1/sync2dDraw")
    public Object sync2dDraw(@RequestBody List<HySync2dDrawInfo> sync2dDrawInfoList){
        logger.info("size :" + sync2dDrawInfoList.size());
        return Result.success();
    }


    @RequestMapping("/run2")
    public Object run2(@RequestBody List<MyTest> tests){

        return tests;

    }


    @RequestMapping("/initPoint")
    public Object initPoint() throws IOException {
        InputStream resourceAsStream = ExcelController.class.getClassLoader().getResourceAsStream("1-商业项目施工图审查要点-建筑.xlsx");
        //FileInputStream inputStream = new FileInputStream("C:\\Users\\lxy\\Desktop\\1-商业项目施工图审查要点-建筑.xlsx");
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook(resourceAsStream);
        XSSFSheet sheet = hssfWorkbook.getSheetAt(7);
        String systemName = "";
        for (int i = 4; i < sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            XSSFCell cell = row.getCell(0);
            // 判断切换系统
            if (!"".equals(cell.getStringCellValue()) && cell.getStringCellValue().contains("、")) {
                StringBuilder builder = new StringBuilder();
                String [] splitName = cell.getStringCellValue().split("、");
                for (int o = 0; o< splitName.length; o++ ) {
                    if(o >0){
                        if (o + 1 < splitName.length){
                            builder = builder.append(splitName[o]+"、") ;
                        } else {
                            builder = builder.append(splitName[o]) ;
                        }
                    }
                }
                systemName = builder.toString();
            }
            // 这个条件下都是子要点,判断有没有小数点，区分是审查内容还是问题类别小计
            row = sheet.getRow(i);
            cell = row.getCell(1);
            String  serialNumber = "";
            XSSFCell cell2 = row.getCell(2);
            XSSFCell cell3 = row.getCell(3);
            if (cell.getCellType() == 1) {
                row.getCell(0).setCellType(Cell.CELL_TYPE_NUMERIC);
                serialNumber = cell.getStringCellValue() ;
            } else {
                serialNumber = String.valueOf(cell.getNumericCellValue() );
            }
            serialNumber = serialNumber.trim();
            if (serialNumber.contains(".") && !cell2.getStringCellValue().isEmpty() && !serialNumber.startsWith("0.0")) {
                java.lang.System.out.println(serialNumber+ " " + cell2.getStringCellValue() + " " + cell3.getStringCellValue());
                addData(systemName,serialNumber,cell2.getStringCellValue(),cell3.getStringCellValue());
            }
        }
        return "ok";
    }

    public void  addData(String systemName,String serialNumber,String content,String pointClassName){
        System system =null;
        // 如果部位分项为空，就不添加
        if (!"".equals(systemName) && systemName != null){
            system = dao.fetch(System.class,Cnd.where("system_name","=",systemName));
            dao.fetchLinks(system,"specialty");
        }
        // 有要点等级的是普通要点
        if (!"".equals(pointClassName) && pointClassName != null){
            Point point = new Point();
            point.setName(content);
            if (system != null){
                point.setSystemId(system.getId());
            }
            PointClass pointClass = dao.fetch(PointClass.class,Cnd.where("point_class_name","=",pointClassName));
            if (pointClass != null){
                point.setPointClassId(pointClass.getId());
            }
            String number = serialNumber.substring(0,3);
            TopPoint topPoint = dao.fetch(TopPoint.class,Cnd.where("number","=",number));
            if (topPoint != null){
                point.setTopPointId(topPoint.getId());
            }
            point.setNumber(serialNumber);
            point =  dao.insert(point);
            dao.insert("wd_re_point_specialty", Chain.make("point_id",point.getId()).add("specialty_id",system.getSpecialtyId()));
        } else {
            TopPoint topPoint =new TopPoint();
            if (system != null){
                topPoint.setSystemId(system.getId());
                topPoint.setSpecialtyId(system.getSpecialtyId());
            }
            topPoint.setName(content);
            topPoint.setNumber(serialNumber);
            topPoint =  dao.insert(topPoint);
            dao.insert("wd_re_point_specialty", Chain.make("point_id",topPoint.getId()).add("specialty_id",system.getSpecialtyId()));
        }
    }

    @RequestMapping("/run")
    @ResponseBody
    public Object run(String[] majorproject){


        return majorproject;

    }



    @RequestMapping("/login")

    public String login(){

        return "login";

    }



    @RequestMapping("/table")
    public String table(){

        return "table";

    }

    @RequestMapping("/initNodeInfo")
    @ResponseBody
    public Object initNodeInfo(){
        List<Map<String,String>> drawingUrls = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("fileName","03.pdf");
        map.put("filePath","http://localhost/drawing/03.pdf");
        drawingUrls.add(map);
        map = new HashMap<>();
        map.put("fileName","04.pdf");
        map.put("filePath","http://localhost/drawing/04.pdf");
        drawingUrls.add(map);
        map = new HashMap<>();
        map.put("fileName","4m.pdf");
        map.put("filePath","http://localhost/drawing/4m.pdf");
        drawingUrls.add(map);
        map = new HashMap<>();
        map.put("fileName","08.pdf");
        map.put("filePath","http://localhost/drawing/08.pdf");
        drawingUrls.add(map);
        map = new HashMap<>();
        map.put("fileName","09.pdf");
        map.put("filePath","http://localhost/drawing/09.pdf");
        drawingUrls.add(map);
        map = new HashMap<>();
        map.put("fileName","10.pdf");
        map.put("filePath","http://localhost/drawing/10.pdf");
        drawingUrls.add(map);

        map = new HashMap<>();
        map.put("fileName","热交换站大样图.pdf");
        map.put("filePath","http://localhost/drawing/热交换站大样图.pdf");
        drawingUrls.add(map);

        map = new HashMap<>();
        map.put("fileName","M2002+-+首层空调通风平面图+1：100.pdf");
        map.put("filePath","http://localhost/drawing/M2002+-+首层空调通风平面图+1：100.pdf");
        drawingUrls.add(map);



        String projectFlowChildrenNodeId= "40bb06b765144d0cbbdc314dc540d0dd";
        String id ="126";

        for (Map<String, String> drawingUrl : drawingUrls) {
            HyNodeInfo nodeInfo = new HyNodeInfo();
            nodeInfo.setFileName(drawingUrl.get("fileName"));
            nodeInfo.setFileId(R.UU16());
            nodeInfo.setFilePath(drawingUrl.get("filePath"));
            nodeInfo.setProjectFlowChildrenNodeId(projectFlowChildrenNodeId);
            dao.insert(nodeInfo);

        }
        return Result.success("success","操作成功!");
    }


    @ResponseBody
    @RequestMapping("/initDrawing")
    public Object initDrawing(){
        String projectFlowChildrenNodeId = "40bb06b765144d0cbbdc314dc540d0dd";
        java.lang.System.out.println("initDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawinginitDrawing");
        // 根据 projectFlowChildrenNodeId 和节点id 查询 nodeInfo
        HyTree parent = dao.fetch(HyTree.class, Cnd.where("parentId", "=", 0));

        getTree_(parent);
        List<HyTree> tree = Arrays.asList(parent);
        initDrawing_(tree,projectFlowChildrenNodeId);


        return Result.success("success","操作成功!");
    }

    private void initDrawing_(List<HyTree> tree,String projectFlowChildrenNodeId ) {

        for (HyTree hyTree : tree) {
           // dao.insert(hyTree);
            List<HyNodeInfo> nodeInfos = dao.query(HyNodeInfo.class, Cnd.where("flowMapModelId", "=", hyTree.getId()).and("projectFlowChildrenNodeId", "=", projectFlowChildrenNodeId));

            for (HyNodeInfo nodeInfo : nodeInfos) {
                try{
                    Map<String, Object> map = fileUploadService.pdf2jpg_(nodeInfo.getFilePath());
                    String jpgPath = (String)map.get("jpgPath");
                    String exName = (String)map.get("exName");
                    Integer width = (Integer)map.get("width");
                    Integer height = (Integer)map.get("height");
                    String fileName = (String)map.get("fileName");
                    Long fid = (Long)map.get("fid");
                    HyDrawing hyDrawing = new HyDrawing();
                    hyDrawing.setFlowMapModelId(hyTree.getId());
                    hyDrawing.setProjectFlowChildrenNodeId(projectFlowChildrenNodeId);
                    hyDrawing.setPngWidth(width);
                    hyDrawing.setPngHeight(height);
                    hyDrawing.setFilePath(jpgPath);
                    hyDrawing.setFileName(fileName);
                    hyDrawing.setFid(fid);
                    dao.insert(hyDrawing);

                }catch (Exception e){

                }
            }

            if (hyTree.getChildren().size()>0){
                initDrawing_(hyTree.getChildren(),projectFlowChildrenNodeId);
            }
        }

    }

    @RequestMapping("/getTree")
    @ResponseBody

    public Object getTree(){
        // 获取最顶层的数据
        HyTree parent = dao.fetch(HyTree.class, Cnd.where("parentId", "=", 0));

        getTree_(parent);
        return parent;


    }

    private void getTree_(HyTree parent) {

        List<HyTree> parents = dao.query(HyTree.class, Cnd.where("parentId", "=", parent.getId()));

        parent.setChildren(parents);
        parents.forEach(item->getTree_(item));


    }
    @ResponseBody
    @RequestMapping("/initTree")
    public Object initTree(){
        String access_token = HyUtil.getHyToken().getAccess_token();
        List<HyTree> tree = HyUtil.getTree(access_token);

        saveTree(tree);

        return null;
    }

    private void saveTree(List<HyTree> tree) {

        for (HyTree hyTree : tree) {
            dao.insert(hyTree);
            if (hyTree.getChildren().size()>0){
                saveTree(hyTree.getChildren());
            }
        }

    }
}
